package fr.sedoo.rbv.geonetwork.request;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fr.sedoo.rbv.geonetwork.domain.GeonetworkUser;
import fr.sedoo.rbv.geonetwork.xml.GeonetworkUserUnmarshaller;

public class UserRequest extends AuthenticatedRequest
{

	private static Logger logger = LoggerFactory.getLogger(UserRequest.class);

	public UserRequest(GeonetworkUser user ) 
	{
		super(user);
	}

	public UserRequest() 
	{
		super();
	}

	public List<GeonetworkUser> execute()
	{
		Element request = new Element("request");
		String userListURL = getConfig().getUserListURL();
		PostMethod post = new PostMethod(userListURL);

		try {
			String postData = getString(new Document(request));
			post.setRequestEntity(new StringRequestEntity(postData,"application/xml", "UTF8"));

			String rawXml = executePostMethod(post);

			logger.debug(rawXml);
			return GeonetworkUserUnmarshaller.fromXML(rawXml);
		}
		catch (Exception e)
		{	
			return new ArrayList<GeonetworkUser>();
		}
		finally {
			post.releaseConnection();
		}
	}

}
